package cn.wolfcode.wms.web.interceptor;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.util.RequiredPermission;
import cn.wolfcode.wms.util.UserContext;
import cn.wolfcode.wms.web.exception.SecurityException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Set;

public class SecurityInterceptor extends HandlerInterceptorAdapter {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee currentUser = UserContext.getCurrentUser();
        if(currentUser.isAdmin()){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if(!method.isAnnotationPresent(RequiredPermission.class)){
            return true;
        }
        Class<?> clz = method.getDeclaringClass();
        String name = clz.getName();
        String expression = name + method.getName();
        Set<String> expressions = UserContext.getExpression();
        if(expressions.contains(expression)){
            return true;
        }
        throw new SecurityException();
    }
}
